//
//  ZJRWViewController.m
//  Estate
//
//  Created by kevin on 16/9/5.
//  Copyright © 2016年 ttsx. All rights reserved.
//
//

#define LINE_Y 20
#import "ZJRWViewController.h"
#import "DefaineCell.h"
#import "B_wuLiaoCell.h"
#import "TableTopStateCell.h"
#import "AttachmentPhotoCell.h"
#import "PictureViewController.h"

#import "InspectProcessRecordModel.h"
#import "UIActionSheet+Common.h"
#import "addJGDBViewController.h"
#import "A_addJLGJViewController.h"
#import "DBYSDetailViewController.h"

@interface ZJRWViewController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

// 整改后的附件ID(fileId)
@property (strong, nonatomic) NSMutableArray *fileIdArr;

// 整改说明
@property (copy, nonatomic) NSString *explain;

// footerView
@property (strong, nonatomic) UIView *footerView;

// 待整改的巡检流程记录
@property (nonatomic, strong) InspectProcessRecordModel *oldModel;

// 待审核的巡检流程记录
@property (nonatomic, strong) InspectProcessRecordModel *newlyModel;

// 当前的巡检记录
@property (nonatomic, strong) InspectProcessRecordModel *currentModel;

// 整改前
@property (nonatomic, strong) TPKeyboardAvoidingTableView *tableView1;

@property (strong, nonatomic) Tweet *curTweet;

@property (strong, nonatomic) NSMutableArray *selectedAssetURLs;

// 整改后
@property (nonatomic, strong) TPKeyboardAvoidingTableView *tableView2;

@property (strong, nonatomic) Tweet *curTweet2;

@property (strong, nonatomic) NSMutableArray *selectedAssetURLs2;

// 流程记录ID
@property (copy, nonatomic) NSString *recordID;

// 当前时间
@property (copy, nonatomic) NSString *nowTime;

// 是否可以编辑
@property (assign, nonatomic) BOOL editing;

// 附件footerView的高度
@property (assign, nonatomic) CGFloat footerHeight;

@end

@implementation ZJRWViewController

- (NSMutableArray *)fileIdArr {
    if (!_fileIdArr) {
        _fileIdArr = [NSMutableArray array];
    }
    return _fileIdArr;
}

-(UITableView *)tableView{
    if(!_tableView){
        _tableView=[[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, DEF_SCREEN_HEIGHT) style:UITableViewStyleGrouped];
        _tableView.delegate=self;
        _tableView.dataSource=self;
    }
    return _tableView;
}

- (UIButton *)duBtn{
    if(!_duBtn){
        _duBtn=[[UIButton alloc]init];
    }
    return _duBtn;
}

// 整改前附件
- (UITableView *)tableView1 {
    if (!_tableView1) {
        _tableView1 = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(0, 90, (DEF_SCREEN_WIDTH - 1) / 2 , self.footerHeight * BIZ) style:UITableViewStylePlain];
        _tableView1.tag = 1000;
        _tableView1.dataSource = self;
        _tableView1.delegate = self;
        _tableView1.bounces = NO;
        _tableView1.showsVerticalScrollIndicator = NO;
        _tableView1.separatorStyle = NO;
        _tableView1.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        [_tableView1 registerClass:[AttachmentPhotoCell class] forCellReuseIdentifier:@"photoCell"];
        [self.footerView addSubview:_tableView1];
        
        [self.tableView1 mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(_footerView).with.offset(90);
            make.bottom.equalTo(_footerView);
            make.left.equalTo(_footerView);
            make.right.equalTo(_footerView).with.offset(-(DEF_SCREEN_WIDTH / 2 + 1));
        }];
    }
    return _tableView1;
}

// 整改后附件
- (UITableView *)tableView2 {
    if (!_tableView2) {
        _tableView2 = [[TPKeyboardAvoidingTableView alloc] initWithFrame:CGRectMake(DEF_SCREEN_WIDTH / 2 + 1, 90, (DEF_SCREEN_WIDTH-1) / 2, self.footerHeight * BIZ) style:UITableViewStylePlain];
        _tableView2.tag = 2000;
        _tableView2.dataSource = self;
        _tableView2.delegate = self;
        _tableView2.bounces=NO;
        _tableView2.showsVerticalScrollIndicator=NO;
        _tableView2.separatorStyle = NO;
        _tableView2.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        //        _tableView2.backgroundColor = [UIColor redColor];
        [_tableView2 registerClass:[AttachmentPhotoCell class] forCellReuseIdentifier:@"photoCell"];
        [self.footerView addSubview:_tableView2];
        
        [self.tableView2 mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(_footerView).with.offset(90);
            make.left.equalTo(_footerView).with.offset(DEF_SCREEN_WIDTH / 2 + 1);
            make.bottom.equalTo(_footerView);
            make.right.equalTo(_footerView);
        }];
    }
    return _tableView2;
}

// 整改前
- (NSMutableArray *)selectedAssetURLs {
    if(!_selectedAssetURLs){
        _selectedAssetURLs=[NSMutableArray array];
    }
    return _selectedAssetURLs;
}

// 整改后
- (NSMutableArray *)selectedAssetURLs2 {
    if (!_selectedAssetURLs2) {
        _selectedAssetURLs2 = [NSMutableArray array];
    }
    return _selectedAssetURLs2;
}

// 组尾footerView
- (UIView *)footerView {
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, self.footerHeight * BIZ)];
        _footerView.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        // 锯齿线
        UIImageView *imageViewS = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
        imageViewS.image = [UIImage imageNamed:@"juchishang"];
        [_footerView addSubview:imageViewS];
        
        // 附件信息
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 10, 100, 40)];
        label.text = @"附件信息";
        label.textColor = [UIColor colorWithRed:0.24 green:0.64 blue:0.61 alpha:1.00];
        [_footerView addSubview:label];
        [self createView];
    }
    return _footerView;
}

- (void)createView {
    
    UIView *line_1=[[UIView alloc]initWithFrame:CGRectMake(0, LINE_Y+50, DEF_SCREEN_WIDTH, 1)];
    line_1.backgroundColor = [UIColor blackColor];
    UIView *line_2=[[UIView alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/2-0.5, LINE_Y+50, 1, DEF_SCREEN_HEIGHT * 2)];
    line_2.backgroundColor = [UIColor blackColor];
    [self.footerView addSubview:line_1];
    [self.footerView addSubview:line_2];
    
    //添加文字
    UILabel *lab_1=[[UILabel alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/8, LINE_Y/2+50, DEF_SCREEN_WIDTH/4, LINE_Y)];
    lab_1.text = @"整改前附件";
    lab_1.textAlignment=1;
    lab_1.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    lab_1.font=[UIFont systemFontOfSize:14.];
    [self.footerView addSubview:lab_1];
    
    UILabel *lab_2 = [[UILabel alloc]initWithFrame:CGRectMake(DEF_SCREEN_WIDTH/8*5, LINE_Y/2+50, DEF_SCREEN_WIDTH/4, LINE_Y)];
    lab_2.text=@"整改后附件";
    lab_2.textAlignment=1;
    lab_2.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
    lab_2.font=[UIFont systemFontOfSize:14.];
    [self.footerView addSubview:lab_2];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"检查任务单";
    
    [self.view addSubview:self.tableView];
    
    self.tableView.bounces = NO;
    self.tableView.showsVerticalScrollIndicator = NO;
    
    //注册单元格
    [self.tableView registerNib:[UINib nibWithNibName:@"B_wuLiaoCell" bundle:nil] forCellReuseIdentifier:@"textCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"DefaineCell" bundle:nil] forCellReuseIdentifier:@"defaine"];
    [self.tableView registerNib:[UINib nibWithNibName:@"TableTopStateCell" bundle:nil] forCellReuseIdentifier:@"topCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"explainTableViewCell" bundle:nil] forCellReuseIdentifier:@"explainCell"];
    
    
    _curTweet = [[Tweet alloc] init];
    _curTweet2 = [[Tweet alloc] init];
    
    // 获取待整改巡检流程记录
    self.oldModel = [self getInspectProcessRecord:@"2"];
    // 整改前图片
    [self getAttachment:self.oldModel.ID andState:@"2"];
    
    // 获取待审核巡检流程记录
    self.newlyModel = [self getInspectProcessRecord:@"4"];
    // 整改后图片
    [self getAttachment:self.newlyModel.ID andState:@"4"];
    [self refresh:nil];
    
    // 当前流程记录
    self.currentModel = [self getInspectProcessRecord];

    // 是否可以编辑
    self.editing = [self.currentModel.INSPECT_ITEM_STATE isEqualToString:@"3"] || ([self.currentModel.INSPECT_ITEM_STATE isEqualToString:@"4"] && [self.currentModel.LOCAL_MODIFY_STATE isEqualToString:@"ADD"]);
    
    if (self.editing) {
        //添加右上方提交按钮
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"wancheng"] style:UIBarButtonItemStyleDone target:self action:@selector(clickSave)];
    }
    // 获取督办单ID
    NSString *superProcessID = [self getSuperProcessID];

    if (self.editing || (superProcessID && ![superProcessID isEqualToString:@""])) {
        // 督办单按钮
        self.duBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        self.duBtn.frame = CGRectMake(DEF_SCREEN_WIDTH - 85, DEF_SCREEN_HEIGHT / 2, 75, 75);
        if(superProcessID && ![superProcessID isEqualToString:@""]){
            NSArray *array = [self getProgessRecordModelArrayWithID:superProcessID];
            ProcessRecordModel *model = [array firstObject];
            if(model.PROCESS_STAGE == PROCESS_STAGE_END){
                self.explain = model.REVIEW_OPINION;
                //此处增加整改后图片
                [self addAssetURLArrayto:self.selectedAssetURLs2 fromImageArrray:model];
                [self refresh:nil];
            }

            [ self.duBtn setBackgroundImage:[UIImage imageNamed:@"xjdbchakan"] forState:UIControlStateNormal];
        }else{
            [ self.duBtn setBackgroundImage:[UIImage imageNamed:@"duban"] forState:UIControlStateNormal];
        }
        [self.view addSubview: self.duBtn];
        [ self.duBtn addTarget:self action:@selector(addDuBan) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refresh:) name:@"RefreshImage_xjzj" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardDidShowNotification
                                               object:nil];
}

- (void)refresh:(id)sender {
    if(self.selectedAssetURLs != nil || self.selectedAssetURLs2 != nil){
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            self.curTweet.selectedAssetURLs = self.selectedAssetURLs;
            self.curTweet2.selectedAssetURLs = self.selectedAssetURLs2;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView1 reloadData];
                [self.tableView2 reloadData];
                [self.tableView reloadData];
            });
        });
    }
}

// 监听弹出键盘后
- (void)keyboardWillShow:(NSNotification *)notification {
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:5 inSection:1] atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

// 添加督办单
- (void)addDuBan {
    WEAKSELF
    // 获取督办单ID
    NSString *superProcessID = [self getSuperProcessID];
    
    if (superProcessID && ![superProcessID isEqualToString:@""]) {
        
        //督办发起可编辑
        BOOL sync=[LSUtility queryProcessIsSync:superProcessID];
        if(sync){
            DeLog(@"查询编辑");
            addJGDBViewController *addGJVC = [[addJGDBViewController alloc] init];
            //督办
            addGJVC.isDB = YES;
            //能否编辑
            addGJVC.edit=YES;
            //流程id
            addGJVC.processId =superProcessID;
            //位置信息
            //            addGJVC.extendInfo = dics[@"EXTEND_INFO"];
            addGJVC.inspect=YES;
            //传入整改前附件
            addGJVC.inspectFileArr=[NSMutableArray arrayWithArray:self.selectedAssetURLs];
            
            [self.navigationController pushViewController:addGJVC animated:YES];
        }else{
            // 获取当前督办单详情
            NSDictionary *dic = [self getDetailWithID:superProcessID];
            DBYSDetailViewController *GJDetail=[[DBYSDetailViewController alloc]init];
            GJDetail.processId = superProcessID;
            GJDetail.addresInfo = dic[@"ADDRES_INFO"];
            GJDetail.beginTime = dic[@"BEGIN_TIME"];
            [self.navigationController pushViewController:GJDetail animated:YES];
        }
        
    } else {
        // 基本信息控制器
        A_addJLGJViewController *basicVC = [[A_addJLGJViewController alloc] init];
        
        basicVC.itemBlock = ^(NSString *recordID) {
            weakSelf.recordID = recordID;
            //绑定督办单到该巡检项
            [self inspectItemProcessId:recordID];
            
            //更换督办单图标
            [ self.duBtn setBackgroundImage:[UIImage imageNamed:@"xjdbchakan"] forState:UIControlStateNormal];
            
        };
        
        //添加督办
        addJGDBViewController *addGJVC = [[addJGDBViewController alloc] init];
        addGJVC.isDB = YES;
        addGJVC.AaddVC = basicVC;
        
        //改动
        //巡检传入标题和描述
        addGJVC.processTitle=self.secondInspectItem;
        addGJVC.processContent=self.currentModel.INSPECT_INFO;
        //传入整改前附件
        addGJVC.inspectFileArr=[NSMutableArray arrayWithArray:self.selectedAssetURLs];
        
        [self.navigationController pushViewController:addGJVC animated:YES];
    }
}

//巡检项绑定督办单
-(void)inspectItemProcessId:(NSString *)processId{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *sql= [NSString stringWithFormat:@"UPDATE INSPECT_USER_ITEM SET  SUPER_PROCESS_ID = '%@', LOCAL_MODIFY_STATE = 'MOD', MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'", processId, DEF_PERSISTENT_GET_OBJECT(@"realname"), [LSUtility getIPAddress],[LSUtility nowTime], self.IUIID];
    
    if([db executeUpdate:sql]) {
        NSLog(@"绑定督办单成功");
    } else {
        NSLog(@"绑定督办单成功失败");
    }
    [db close];
    
}

// 获取督办单ID
- (NSString *)getSuperProcessID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM INSPECT_USER_ITEM WHERE ID = '%@'", self.IUIID];
    FMResultSet *result = [db executeQuery:sql];
    
    NSString *superProcessID;
    while ([result next]) {
        superProcessID = [result stringForColumn:@"SUPER_PROCESS_ID"];
    }
    [db close];
    return superProcessID;
}

// 获取当前督办单详情
- (NSDictionary *)getDetailWithID:(NSString *)ID {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM PROCESS WHERE ID = '%@'", ID];
    FMResultSet *result = [db executeQuery:sql];
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSString *extendInfo;
    NSString *beginTime;
    while ([result next]) {
        extendInfo = [result stringForColumn:@"ADDRES_INFO"];
        beginTime = [result stringForColumn:@"BEGIN_TIME"];
        
        if (!extendInfo) {
            extendInfo = @"";
        }
        [dic setValue:extendInfo forKey:@"ADDRES_INFO"];
        [dic setValue:beginTime forKey:@"BEGIN_TIME"];
    }
    [db close];
    return dic;
}
-(void)addAssetURLArrayto:(NSMutableArray *)assetURLArray fromImageArrray:(ProcessRecordModel *)recordModel{
    NSArray *imageArr = [LSUtility dictionaryWithJsonString:recordModel.FILEINFOS];
    
    if (imageArr.count>0) {
        for (NSDictionary *imageDic in imageArr) {
            NSString *fileId = imageDic[@"fileId"];
            NSString *fileName = [LSUtility queryAttachment:fileId][@"FILE_NAME"];
            NSString *filePath = [DEF_FILE_PATH stringByAppendingString:
                                  [NSString stringWithFormat:@"/%@",fileName]];
            [assetURLArray addObject:filePath];
        }
    }
}
//获取督办单的流程记录
- (NSMutableArray *)getProgessRecordModelArrayWithID:(NSString *)ID{
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT *, time(CREATE_TIME), date(CREATE_TIME) FROM PROCESS_RECORD WHERE PROCESS_ID = '%@' ORDER BY CREATE_TIME DESC", ID];
    FMResultSet *result = [db executeQuery:sql];
    NSMutableArray *processRecordArray = [NSMutableArray array];
    
    while ([result next]) {
        ProcessRecordModel *prModel = [[ProcessRecordModel alloc] init];
        prModel.ID= [result stringForColumn:@"ID"];
        prModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        prModel.PROCESS_ID = [result stringForColumn:@"PROCESS_ID"];
        prModel.ADDRESS_ID = [result stringForColumn:@"ADDRESS_ID"];
        prModel.ADDRES_INFO = [result stringForColumn:@"ADDRES_INFO"];
        prModel.PROCESS_TYPE = [result intForColumn:@"PROCESS_TYPE"];
        prModel.PROCESS_STAGE = [result intForColumn:@"PROCESS_STAGE"];
        prModel.RECORD_USER = [result stringForColumn:@"RECORD_USER"];
        prModel.PROBLEM_TYPE = [result intForColumn:@"PROBLEM_TYPE"];
        prModel.RECORD_MASTER = [result stringForColumn:@"RECORD_MASTER"];
        prModel.RECIFY_USER = [result stringForColumn:@"RECIFY_USER"];
        prModel.RECIFY_UNIT = [result stringForColumn:@"RECIFY_UNIT"];
        prModel.SEVERITY = [result stringForColumn:@"SEVERITY"];
        prModel.END_TIME = [result stringForColumn:@"END_TIME"];
        prModel.SEND_TIME = [result stringForColumn:@"SEND_TIME"];
        prModel.SEND_TYPE = [result intForColumn:@"SEND_TYPE"];
        prModel.PROCESS_TITLE = [result stringForColumn:@"PROCESS_TITLE"];
        prModel.PROCESS_CONTENT = [result stringForColumn:@"PROCESS_CONTENT"];
        prModel.PROCESS_REQUIRED = [result stringForColumn:@"PROCESS_REQUIRED"];
        prModel.PROCESS_DESC = [result stringForColumn:@"PROCESS_DESC"];
        prModel.SUBMITTORS = [result stringForColumn:@"SUBMITTORS"];
        prModel.PUT_USER = [result stringForColumn:@"PUT_USER"];
        prModel.REVIEW_OPINION = [result stringForColumn:@"REVIEW_OPINION"];
        prModel.FILEINFOS = [result stringForColumn:@"FILEINFOS"];
        prModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        prModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        prModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        prModel.CREATE_DATE = [result stringForColumn:@"date(CREATE_TIME)"];
        prModel.SUBCREATE_TIME = [result stringForColumn:@"time(CREATE_TIME)"];
        prModel.zhuangtai = [result intForColumn:@"REVIEW_STATE"];
        prModel.REVIEW_USER = [result stringForColumn:@"REVIEW_USER"];
        //本地状态 用于判断能否编辑
        prModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        [processRecordArray addObject:prModel];
    }
    [db close];
    return processRecordArray;
}

// 获取巡检记录
- (InspectProcessRecordModel *)getInspectProcessRecord:(NSString *)state {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 查找属于当前巡检流程的巡检流程记录(二级巡检项)
    NSString *IPRStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE INSPECT_USER_ITEM_ID = '%@' AND INSPECT_ITEM_STATE = '%@' ORDER BY CREATE_TIME DESC", self.IUIID, state];
    FMResultSet *result = [db executeQuery:IPRStr];
    
    InspectProcessRecordModel *iPRModel = [[InspectProcessRecordModel alloc] init];
    while ([result next]) {
        iPRModel.ID = [result stringForColumn:@"ID"];
        iPRModel.INSPECT_USER_ITEM_ID = [result stringForColumn:@"INSPECT_USER_ITEM_ID"];
        iPRModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        iPRModel.INSPECT_PROCESS_ID = [result stringForColumn:@"INSPECT_PROCESS_ID"];
        iPRModel.INSPECT_USER_ID = [result stringForColumn:@"INSPECT_USER_ID"];
        iPRModel.INSPECT_ITEM_ID = [result stringForColumn:@"INSPECT_ITEM_ID"];
        iPRModel.INSPECT_ITEM_STATE = [result stringForColumn:@"INSPECT_ITEM_STATE"];
        iPRModel.INSPECT_INFO = [result stringForColumn:@"INSPECT_INFO"];
        iPRModel.INSPECT_DESC = [result stringForColumn:@"INSPECT_DESC"];
        iPRModel.INSPECT_RESULT = [result stringForColumn:@"INSPECT_RESULT"];
        iPRModel.INSPECT_SCORE = [result stringForColumn:@"INSPECT_SCORE"];
        iPRModel.INSPECT_ITEM_RECIFICATE_LEADER = [result stringForColumn:@"INSPECT_ITEM_RECIFICATE_LEADER"];
        iPRModel.INSPECT_RECIFICATE_DESC = [result stringForColumn:@"INSPECT_RECIFICATE_DESC"];
        iPRModel.INSPECT_RECIFICATE_REVIEW_USER = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW_USER"];
        iPRModel.INSPECT_RECIFICATE_REVIRE_SCORE = [result stringForColumn:@"INSPECT_RECIFICATE_REVIRE_SCORE"];
        iPRModel.INSPECT_RECIFICATE_REVIEW = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW"];
        iPRModel.INSPECT_DO_TIME = [result stringForColumn:@"INSPECT_DO_TIME"];
        iPRModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        iPRModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        
        iPRModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        iPRModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        iPRModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        iPRModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        iPRModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        break;
    }
    [db close];
    return iPRModel;
}

// 获取最新的巡检记录
- (InspectProcessRecordModel *)getInspectProcessRecord {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    // 查找属于当前巡检流程的巡检流程记录(二级巡检项)
    NSString *IPRStr = [NSString stringWithFormat:@"SELECT * FROM INSPECT_PROCESS_RECORD WHERE INSPECT_USER_ITEM_ID = '%@' ORDER BY CREATE_TIME DESC", self.IUIID];
    FMResultSet *result = [db executeQuery:IPRStr];
    
    InspectProcessRecordModel *iPRModel = [[InspectProcessRecordModel alloc] init];
    while ([result next]) {
        
        iPRModel.ID = [result stringForColumn:@"ID"];
        iPRModel.INSPECT_USER_ITEM_ID = [result stringForColumn:@"INSPECT_USER_ITEM_ID"];
        iPRModel.PRO_ID = [result stringForColumn:@"PRO_ID"];
        iPRModel.INSPECT_PROCESS_ID = [result stringForColumn:@"INSPECT_PROCESS_ID"];
        iPRModel.INSPECT_USER_ID = [result stringForColumn:@"INSPECT_USER_ID"];
        iPRModel.INSPECT_ITEM_ID = [result stringForColumn:@"INSPECT_ITEM_ID"];
        iPRModel.INSPECT_ITEM_STATE = [result stringForColumn:@"INSPECT_ITEM_STATE"];
        iPRModel.INSPECT_INFO = [result stringForColumn:@"INSPECT_INFO"];
        iPRModel.INSPECT_DESC = [result stringForColumn:@"INSPECT_DESC"];
        iPRModel.INSPECT_RESULT = [result stringForColumn:@"INSPECT_RESULT"];
        iPRModel.INSPECT_SCORE = [result stringForColumn:@"INSPECT_SCORE"];
        iPRModel.INSPECT_ITEM_RECIFICATE_LEADER = [result stringForColumn:@"INSPECT_ITEM_RECIFICATE_LEADER"];
        iPRModel.INSPECT_RECIFICATE_DESC = [result stringForColumn:@"INSPECT_RECIFICATE_DESC"];
        iPRModel.INSPECT_RECIFICATE_REVIEW_USER = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW_USER"];
        iPRModel.INSPECT_RECIFICATE_REVIRE_SCORE = [result stringForColumn:@"INSPECT_RECIFICATE_REVIRE_SCORE"];
        iPRModel.INSPECT_RECIFICATE_REVIEW = [result stringForColumn:@"INSPECT_RECIFICATE_REVIEW"];
        iPRModel.INSPECT_DO_TIME = [result stringForColumn:@"INSPECT_DO_TIME"];
        iPRModel.EXTEND_INFO = [result stringForColumn:@"EXTEND_INFO"];
        iPRModel.CREATE_USER_NAME = [result stringForColumn:@"CREATE_USER_NAME"];
        iPRModel.CREATE_TIME = [result stringForColumn:@"CREATE_TIME"];
        iPRModel.CREATE_IP = [result stringForColumn:@"CREATE_IP"];
        iPRModel.MODIFY_USER_NAME = [result stringForColumn:@"MODIFY_USER_NAME"];
        iPRModel.MODIFY_IP = [result stringForColumn:@"MODIFY_IP"];
        iPRModel.MODIFY_TIME = [result stringForColumn:@"MODIFY_TIME"];
        iPRModel.LOCAL_MODIFY_STATE = [result stringForColumn:@"LOCAL_MODIFY_STATE"];
        break;
    }
    [db close];
    return iPRModel;
}


// 获取附件数据
- (void)getAttachment:(NSString *)fileId andState:(NSString *)state {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT * FROM ATTACHMENT WHERE FILE_ID = '%@'", fileId];
    FMResultSet *result = [db executeQuery:sql];
    
    while ([result next]) {
        // 记录图片名
        NSString *fileName = [result stringForColumn:@"FILE_NAME"];
        NSString *filePath = [DEF_FILE_PATH stringByAppendingString:
                              [NSString stringWithFormat:@"/%@",fileName]];
        NSString *ID = [result stringForColumn:@"ID"];
        
        if ([state isEqualToString:@"2"]) {
            [self.selectedAssetURLs addObject:filePath];
            
        } else if ([state isEqualToString:@"4"]) {
            [self.selectedAssetURLs2 addObject:filePath];
            // 整改后的附件表的ID
            [self.fileIdArr addObject:ID];
        }
    }
    [db close];
}

#pragma  mrak--UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (tableView.tag == 1000 || tableView.tag == 2000) {
        return 1;
        
    } else {
        return 3;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001;
}

// 组尾高度
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (tableView.tag == 1000 || tableView.tag == 2000) {
        return 0.001;
        
    } else {
        if (section == 2) {
            if (self.selectedAssetURLs.count > self.selectedAssetURLs2.count) {
                self.footerHeight = ((self.selectedAssetURLs.count + 1) * 132 + 90) * BIZ;
                
            } else if (self.selectedAssetURLs2.count >= self.selectedAssetURLs.count) {
                
                if (self.selectedAssetURLs2.count == 9) {
                    self.footerHeight = (self.selectedAssetURLs2.count * 132 + 95) * BIZ;
                    
                } else {
                    self.footerHeight = ((self.selectedAssetURLs2.count + 1) * 132 + 90) * BIZ;
                }
            }
            return self.footerHeight;
            
        } else {
            return 25;
        }
    }
}

// 组尾视图
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    if (tableView.tag == 1000 || tableView.tag == 2000) {
        return nil;
    } else {
        if (section == 2) {
            return self.footerView;
            
        } else {
            UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 25)];
            view.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
            
            UIImageView *imageViewS = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, DEF_SCREEN_WIDTH, 8)];
            imageViewS.image = [UIImage imageNamed:@"juchishang"];
            UIImageView *imageViewX = [[UIImageView alloc]initWithFrame:CGRectMake(0, 17, DEF_SCREEN_WIDTH, 8)];
            imageViewX.image = [UIImage imageNamed:@"juchixia"];
            
            [view addSubview:imageViewS];
            [view addSubview:imageViewX];
            return view;
        }
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (tableView.tag == 1000) {
        return 1;
        
    } else if (tableView.tag == 2000) {
        return 1;
        
    } else {
        if(section == 0) {
            return 4;
            
        } else if (section == 1) {
            return 6;
            
        } else {
            return 1;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    long section = indexPath.section;
    long row = indexPath.row;
    
    if (tableView.tag == 1000) {
        return [AttachmentPhotoCell cellHeightWithObj:_curTweet];
        
    } else if (tableView.tag == 2000) {
        return [AttachmentPhotoCell cellHeightWithObj:_curTweet2];
        
    } else {
        if(section == 0) {
            return 44;
        } else if (section == 1){
            if(row == 0 || row == 3 || row == 5) {
                return 44;
            } else {
                return 100;
            }
        } else {
            return 100;
        }
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    long section = indexPath.section;
    long row = indexPath.row;
    WEAKSELF
    
    if (tableView.tag == 1000) {
        AttachmentPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"photoCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
        cell.curTweet = _curTweet;
        cell.isEdit = NO;
        return cell;
        
    } else if (tableView.tag == 2000) {
        if (self.editing) {
            AttachmentPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"photoCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
            cell.curTweet = _curTweet2;
            cell.isEdit = YES;
            
            cell.addPicturesBlock = ^(){
                [weakSelf showActionForPhoto];
            };
            cell.deleteTweetImageBlockUrl= ^(TweetImage *toDelete,NSString *deUrl){
                //移除图片
                [weakSelf.curTweet2 deleteATweetImage:toDelete];
                //移除数组
                [weakSelf.selectedAssetURLs2 removeObject:deUrl];
                
                [weakSelf refresh:nil];
            };
            return cell;
            
        } else {
            AttachmentPhotoCell *cell = [tableView dequeueReusableCellWithIdentifier:@"photoCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.backgroundColor = [UIColor colorWithRed:0.95 green:0.96 blue:0.96 alpha:1.00];
            cell.curTweet = _curTweet2;
            cell.isEdit = NO;
            return cell;
        }
        
    } else {
        if (section == 0) {
            if (row == 0) {
                TableTopStateCell *cell = [tableView dequeueReusableCellWithIdentifier:@"topCell" forIndexPath:indexPath];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.title.text = [NSString stringWithFormat: @"%@%@检查任务单", [LSUtility dateNow], [LSUtility getuserIdByUserName:self.currentModel.INSPECT_USER_ID][@"REAL_NAME"]];
                return cell;
                
            } else if (row == 1) {  // 项目名
                DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle=UITableViewCellSelectionStyleNone;
                dCell.title.text = @"项   目:";
                dCell.text.text = DEF_PERSISTENT_GET_OBJECT(@"proname");
                return dCell;
                
            } else if (row == 2) {  // 记录人
                DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle=UITableViewCellSelectionStyleNone;
                dCell.title.text = @"记录人:";
                dCell.text.text = [LSUtility getuserIdByUserName:self.currentModel.INSPECT_USER_ID][@"REAL_NAME"];
                return dCell;
                
            } else {    // 时间
                DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle=UITableViewCellSelectionStyleNone;
                dCell.title.text=@"时   间:";
                dCell.text.text = self.currentModel.CREATE_TIME;
                return dCell;
            }
            
        } else if (section == 1) {    // 一级检查项
            if(row==0){
                DefaineCell *dCell=[tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle=UITableViewCellSelectionStyleNone;
                dCell.title.text=@"检 查 类:";
                dCell.text.text = self.firstInspectItem;
                return dCell;
                
            } else if (row == 1) {  // 二级检查项
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.isEdit = NO;
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查内容:";
                cell.text.text = self.secondInspectItem;
                return cell;
                
            } else if (row == 2) {  // 检查情况
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"检查情况:";
                cell.isEdit = NO;
                cell.text.text = self.currentModel.INSPECT_INFO;
                return cell;
                
            } else if (row == 3) {  // 结论
                DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                dCell.title.text = @"结   论:";
                
                if ([self.currentModel.INSPECT_RESULT isEqualToString:@"0"]) {
                    dCell.text.text = @"不合格";
                    
                } else if ([self.currentModel.INSPECT_RESULT isEqualToString:@"1"]) {
                    dCell.text.text = @"合格";
                    
                } else if ([self.currentModel.INSPECT_RESULT isEqualToString:@"2"]) {
                    dCell.text.text = @"不涉及";
                }
                return dCell;
                
            } else if (row == 4) {  // 备注(检查说明)
                B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
                cell.selectionStyle=UITableViewCellSelectionStyleNone;
                cell.title.text = @"备   注:";
                cell.isEdit = NO;
                cell.text.text = self.currentModel.INSPECT_DESC;
                cell.text.placeholder = @"";
                return cell;
                
            } else {    // 分数
                DefaineCell *dCell = [tableView dequeueReusableCellWithIdentifier:@"defaine" forIndexPath:indexPath ];
                dCell.selectionStyle = UITableViewCellSelectionStyleNone;
                dCell.title.text = @"分   数:";
                dCell.text.text = self.currentModel.INSPECT_SCORE;
                return dCell;
            }
        } else {      // 说明
            B_wuLiaoCell *cell=[tableView dequeueReusableCellWithIdentifier:@"textCell" forIndexPath:indexPath];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.title.text = @"说     明:";
            cell.isEdit = YES;

            if (!self.editing) {
                cell.isEdit = NO;
                cell.text.placeholder = @"";
                
            } else {
                
                cell.text.placeholder = @"请输入说明";
            }
            
            cell.text.text = self.explain ? self.explain : self.currentModel.INSPECT_RECIFICATE_DESC;
            self.explain = self.explain ? self.explain : self.currentModel.INSPECT_RECIFICATE_DESC;
            cell.textValueChangedBlock = ^(NSString *cStr) {
                self.explain = cStr;
            };
            return cell;
        }
    }
}

#pragma mark--保存
- (void)clickSave {
    if (!self.explain || [self.explain isEqualToString:@""]) {
        [LSUtility showToastWithMessage:@"请输入说明" inView:self.navigationController.view Andtime:1.];
        
    } else {
        self.nowTime = [LSUtility nowTime];
        
        // 修改任务表
        [self modifyInspectProcess];
        // 修改用户巡检项表
        [self modifyInspectUserItem];
        // 查找当前巡检项状态为3的条数
        int count3 = [LSUtility getInspectItemCountByUserItemID:self.currentModel.INSPECT_USER_ITEM_ID withState:@"3"];
        // 查找当前巡检项状态为4的条数
        int count4 = [LSUtility getInspectItemCountByUserItemID:self.currentModel.INSPECT_USER_ITEM_ID withState:@"4"];
        
        if (count3 > count4) {     // 当前流程为待整改
            // 新增巡检记录表
            [self addFlowRecordData];
            
        } else {    // 当前流程为待审核
            // 先删除整改后的图片附件
            [self deleteLastData];
            // 修改巡检记录
            [self modifyInspectRecord];
            // 新增附件表
            [self insertAttachment:self.newlyModel.ID];
        }
        
        // 刷新巡检列表状态
        [[NSNotificationCenter defaultCenter] postNotificationName:@"AKeyCombination" object:nil];
        // 通知首页刷新数据
        [[NSNotificationCenter defaultCenter] postNotificationName:@"home" object:nil];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}

// 修改巡检任务表
- (void)modifyInspectProcess {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *iprSql = [NSString stringWithFormat:@"UPDATE INSPECT_PROCESS SET INSPECT_STATE = '4', MODIFY_TIME = '%@', MODIFY_IP = '%@', LOCAL_MODIFY_STATE = 'MOD' WHERE ID = '%@'", self.nowTime, [LSUtility getIPAddress], self.IPID];
    
    if([db executeUpdate:iprSql]) {
        NSLog(@"修改巡检任务成功");
        
    } else {
        NSLog(@"修改巡检任务失败");
    }
    [db close];
}


#pragma mark - 新增巡检流程记录
- (void)addFlowRecordData {
    NSString *ID = [NSUUID UUID].UUIDString;
    [self insertAttachment:ID];
    
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    DBHelper *dbhelper = [DBHelper help];
    
    // 当前用户名
    //    NSString *nameStr = [LSUtility getuserIdByUserName:USERID][@"REAL_NAME"];
    
    //字段及对应值
    NSDictionary *pragameDic = [NSDictionary dictionary];
    pragameDic = @{
                   @"ID":ID,
                   @"INSPECT_USER_ITEM_ID":DEFISNUL(self.oldModel.INSPECT_USER_ITEM_ID),
                   @"PRO_ID":DEFISNUL(self.oldModel.PRO_ID),
                   @"INSPECT_PROCESS_ID":DEFISNUL(self.oldModel.INSPECT_PROCESS_ID),
                   @"INSPECT_USER_ID":DEFISNUL(self.oldModel.INSPECT_USER_ID),
                   @"INSPECT_ITEM_ID":DEFISNUL(self.oldModel.INSPECT_ITEM_ID),
                   @"INSPECT_ITEM_STATE":@"4",
                   @"INSPECT_INFO":DEFISNUL(self.oldModel.INSPECT_INFO),
                   @"INSPECT_DESC":DEFISNUL(self.oldModel.INSPECT_DESC),
                   @"INSPECT_RESULT":DEFISNUL(self.oldModel.INSPECT_RESULT),
                   @"INSPECT_SCORE":DEFISNUL(self.oldModel.INSPECT_SCORE),
                   @"INSPECT_ITEM_RECIFICATE_LEADER":DEFISNUL(self.oldModel.INSPECT_ITEM_RECIFICATE_LEADER),
                   @"INSPECT_RECIFICATE_DESC":DEFISNUL(self.explain),
                   @"INSPECT_RECIFICATE_REVIEW_USER":DEFISNUL(self.oldModel.INSPECT_RECIFICATE_REVIEW_USER),
                   @"INSPECT_RECIFICATE_REVIRE_SCORE":DEFISNUL(self.oldModel.INSPECT_RECIFICATE_REVIRE_SCORE),
                   @"INSPECT_RECIFICATE_REVIEW":DEFISNUL(self.oldModel.INSPECT_RECIFICATE_REVIEW),
                   @"INSPECT_DO_TIME":DEFISNUL(self.oldModel.INSPECT_DO_TIME),
                   @"EXTEND_INFO":DEFISNUL(self.oldModel.EXTEND_INFO),
                   @"CREATE_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"CREATE_TIME":DEFISNUL(self.nowTime),
                   @"CREATE_IP":[LSUtility getIPAddress],
                   @"MODIFY_USER_NAME":DEF_PERSISTENT_GET_OBJECT(@"realname"),
                   @"MODIFY_IP":[LSUtility getIPAddress],
                   @"MODIFY_TIME":DEFISNUL(self.nowTime),
                   @"LOCAL_MODIFY_USER_NAME":@"",
                   @"LOCAL_MODIFY_TIME":@"",
                   @"LOCAL_MODIFY_STATE":@"ADD",
                   };
    BOOL isAdd = [dbhelper DataBase:db insertKeyValues:pragameDic intoTable:INSPECT_PROCESS_RECORD];
    
    if (isAdd) {
        NSLog(@"巡检记录添加成功");
        
    } else {
        NSLog(@"巡检记录添加失败");
    }
}

// 先删除整改后的图片附件
-(void)deleteLastData {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    for (int i = 0; i < self.fileIdArr.count; i++) {
        NSString *sql = [NSString stringWithFormat:@"DELETE FROM ATTACHMENT WHERE ID = '%@'",self.fileIdArr[i]];
        
        if ([db executeUpdate:sql]) {
            NSLog(@"删除成功");
        } else {
            NSLog(@"删除失败");
        }
    }
    [db close];
}

// 修改巡检记录
- (void)modifyInspectRecord {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    NSString *iprSql = [NSString stringWithFormat:@"UPDATE INSPECT_PROCESS_RECORD SET INSPECT_ITEM_STATE = '4', INSPECT_RECIFICATE_DESC = '%@', MODIFY_TIME = '%@', MODIFY_IP = '%@' WHERE ID = '%@'", self.explain, self.nowTime, [LSUtility getIPAddress], self.newlyModel.ID];
    
    if([db executeUpdate:iprSql]) {
        NSLog(@"修改巡检记录成功");
        
    } else {
        NSLog(@"修改巡检记录失败");
    }
    [db close];
}


#pragma mark - 先新增附件表
- (NSArray *)insertAttachment:(NSString *)recordIds {
    NSArray *rFileArr;
    if (self.selectedAssetURLs2.count > 0) {
        rFileArr = [LSUtility insertAttachmentFromArray:self.selectedAssetURLs2 andRecordId:recordIds andType:@"INSPECT_01" andRecifyState:@"1"];
    }
    return rFileArr;
}

#pragma mark - 修改用户巡检项表
- (void)modifyInspectUserItem {
    FMDatabase *db = [FMDatabase databaseWithPath:DEF_DB_DATABASEPATH];
    [db open];
    
    NSString *IUISql  = [NSString stringWithFormat:@"UPDATE INSPECT_USER_ITEM SET INSPECT_CURRENT_STATE = '4', LOCAL_MODIFY_STATE = 'MOD', MODIFY_USER_NAME = '%@', MODIFY_IP = '%@', MODIFY_TIME = '%@' WHERE ID = '%@'", DEF_PERSISTENT_GET_OBJECT(@"realname"), [LSUtility getIPAddress], self.nowTime,self.IUIID];
    
    if([db executeUpdate:IUISql]) {
        NSLog(@"修改用户巡检项状态成功");
    } else {
        NSLog(@"修改用户巡检项状态失败");
    }
    [db close];
}

// 将字典或者数组转化为JSON串
- (NSString *)toJSONData:(id)theData{
    NSString *jsonString = nil;
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:theData
                                                       options:0
                                                         error:&error];
    
    if ([jsonData length] != 0 && error == nil){
        jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    }else{
        NSLog(@"转JSON失败%@", error);
    }
    return jsonString;
}

/*
 *  此方法让cell横线置顶
 */
-(void)viewDidLayoutSubviews {
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPat{
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}

#pragma mark UIActionSheet M

- (void)showActionForPhoto{
    [self.view endEditing:YES];
    //    @weakify(self);
    [[UIActionSheet bk_actionSheetCustomWithTitle:nil buttonTitles:@[@"拍照", @"从相册选择"] destructiveTitle:nil cancelTitle:@"取消" andDidDismissBlock:^(UIActionSheet *sheet, NSInteger index) {
        
        [self photoActionSheet:sheet DismissWithButtonIndex:index];
        
    }] showInView:self.view];
}

- (void)photoActionSheet:(UIActionSheet *)sheet DismissWithButtonIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        //拍照
        if (self.curTweet2.tweetImages.count >= 9) {//照片最多这么多
            kTipAlert(@"最多只可选择9张照片，已经选满了。先去掉一张照片再拍照呗～");
            return;
        }
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.delegate = self;
        picker.allowsEditing = NO;//设置可编辑
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];//进入照相界面
        
    }else if (buttonIndex == 1){
        PictureViewController *picCtr=[[PictureViewController alloc]init];
        picCtr.flag = @"file";
        NSMutableArray *array = [self.selectedAssetURLs2 valueForKeyPath:@"@distinctUnionOfObjects.self"];
        picCtr.selectedImages = [[NSMutableArray alloc] initWithArray:array];
        picCtr.selectedImageBlock = ^(NSMutableArray *array) {
            //            for (NSString *path in array) {
            //添加图片路径到已选数组
            //            }
            self.selectedAssetURLs2 = array;
        };
        [self.navigationController pushViewController:picCtr animated:YES];
    }
}

#pragma mark UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    UIImage *image=[info objectForKey:UIImagePickerControllerOriginalImage];
    self.curTweet.editImageView = [[EditImageView alloc]initWithImage:image];
    WEAKSELF
    self.curTweet.editImageView.completeBlock = ^(NSString *path) {
        [weakSelf.curTweet2 addASelectedAssetURL:path];
        [weakSelf.selectedAssetURLs2 addObject:path];
        [weakSelf.tableView2 reloadData];
        
        [weakSelf.tableView reloadData];
    };
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        [self.view endEditing:YES];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"RefreshImage_xjzj" object:nil];
}


@end



